<template>
  <div class="chat-container">
    <!-- 左侧用户列表 -->
    <div class="user-list">
      <ul>
        <li
            v-for="user in uniqueUsers"
            :key="user.userId"
            @click="selectUser(user)"
            :class="{'selected-user': selectedUser && selectedUser.userId === user.userId}"
        >
          <img v-if="user.userAvatar" :src="user.userAvatar" alt="User Avatar" class="user-avatar" />
          <span>{{ user.userName || '未知用户' }}</span>
        </li>
      </ul>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat-window">
      <div v-if="selectedUser">
        <!-- 消息列表 -->
        <div class="chat-box" ref="chatBox">
          <div
              class="chat-message"
              v-for="(message, index) in messages"
              :key="index"
              :class="{
      'user-message': message.merchantId === null,
      'service-message': message.merchantId !== null
    }"
          >
            <!-- 消息内容 -->
            <div class="message-wrapper"  >
              <template v-if="message.merchantId === null">
                <div class="avatar">
                  <img :src="message.userAvatar || userAvatar" alt="用户头像" class="avatar-image" />
                </div>
                <div class="message-content-wrapper content-left">
                  <div class="message-author">{{ selectedUser.userName || '未知用户' }}</div>
                  <div class="message-content">
                    <template v-if="message.messageType === 'image'">
                      <img
                          :src="message.imageUrl"
                          alt="图片消息"
                          class="message-image user-message-image"
                          @click="openImagePreview(message.imageUrl)"
                      />
                    </template>
                    <!-- 用户消息 -->
                    <template v-if="message.messageType === 'good'">
                      <!-- 商品卡片消息 -->
                      <div class="product-card-message">
                        <img
                            :src="message.goodImg"
                            alt="商品图片"
                            class="message-image"
                            @click="openImagePreview(message.goodImg)"
                        />
                        <div class="product-info-message">
                          <h3>{{ message.goodName }}</h3>
                          <div class="product-price">￥{{ message.goodprice }}</div>
                        </div>
                      </div>
                    </template>
                    <template v-else>
                      {{ message.messageText }}
                    </template>
                  </div>
                </div>
              </template>

              <!-- 客服消息 -->
              <template v-else>
                <div class="message-content-wrapper content-right">
                  <div class="message-author">{{ message.merchantName || "客服" }}</div>
                  <div class="message-content">
                    <template v-if="message.messageType === 'image'">
                      <img
                          :src="message.imageUrl"
                          alt="客服图片消息"
                          class="message-image service-message-image"
                          @click="openImagePreview(message.imageUrl)"
                      />
                    </template>
                    <template v-else>
                      {{ message.messageText }}
                    </template>
                  </div>
                </div>
                <div class="avatar avatar-right">
                  <img :src="message.merchantAvatar || serviceAvatar" alt="客服头像" class="avatar-image" />
                </div>
              </template>
            </div>
          </div>

          <!-- 如果没有消息，显示一个占位的空消息 -->
          <div v-if="messages.length === 0" class="chat-placeholder">
            <p>暂无消息，开始聊天吧！</p>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="input-area">
            <a-icon type="plus-circle" style="font-size: 25px;padding: 5px;" @click="triggerFileInput" />
          <input
              type="file"
              ref="fileInput"
              style="display: none;"
              accept="image/*"
              @change="uploadImage"
          />
          <input
              v-model="newMessage"
              @keydown.enter="sendMessage"
              type="text"
              placeholder="输入您的消息..."
              class="message-input"
          />
          <button @click="sendMessage" class="send-button">发送</button>
        </div>
      </div>
      <div v-else>
        <p>请选择你要回复的用户。</p>
      </div>
    </div>

    <!-- 图片预览弹窗 -->
    <div v-if="isPreviewingImage" class="image-preview-overlay" @click="closeImagePreview">
      <div class="image-preview-content" @click.stop>
        <img :src="previewImageUrl" alt="预览图片" />
      </div>
    </div>
  </div>
</template>

<script>
import {METHOD, request} from "@/utils/request";
import Cookie from "js-cookie";
import 'ant-design-vue/dist/antd.css';


export default {
  name: 'ChatWindow',
  data() {
    return {
      users: [],  // 所有用户列表
      uniqueUsers: [], // 去重后的用户列表
      selectedUser: null,  // 当前选择的用户
      messages: [],  // 当前用户的聊天记录
      newMessage: '',  // 用户输入的消息
      isPreviewingImage: false, // 是否正在预览图片
      previewImageUrl: "", // 当前预览的图片 URL
      intervalId: null,  // 用来存储定时器 ID
      shangchuanimg: `${window.location.protocol}//${window.location.hostname}:8080/api/uploads/shangchuan.png`,
    };
  },
  watch: {
    // 监听 messages 变化，每次消息增加时滚动到底部
    messages() {
      this.scrollToBottom();
    },
  },
  methods: {
    // 打开图片预览
    openImagePreview(imageUrl) {
      this.previewImageUrl = imageUrl;
      this.isPreviewingImage = true;
    },
    // 关闭图片预览
    closeImagePreview() {
      this.previewImageUrl = "";
      this.isPreviewingImage = false;
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox; // 使用 $refs 获取消息容器
        if (chatBox) {
          chatBox.scrollTop = chatBox.scrollHeight; // 滚动到底部
        }
      });
    },
    // 获取所有用户
    fetchUsers() {
      try {
        // 调用后端 API 获取用户信息
        request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/messages/getAll`,
            METHOD.GET
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        ).then((response) => {
          const data = response.data && response.data.data;  // Check if data exists
          if (!data) {
            throw new Error('No data found');
          }

          data.forEach(user => {
            const defaultAvatar = `${window.location.protocol}//${window.location.hostname}:8080/api/uploads/default_avatar.png`;
            user.userAvatar = user.userAvatar && user.userAvatar !== "http://localhost:8080" && user.userAvatar !== `${window.location.protocol}//${window.location.hostname}:8080` ? user.userAvatar : defaultAvatar;

            // 如果没有用户名，设置默认用户名
            if (!user.userName) {
              user.userName = "用户" + user.userMobile;
            }
          });
          // 更新用户列表
          this.users = data;
          this.fetch(data)
          this.users = response.data.data;
          this.uniqueUsers = this.removeDuplicateUsers(this.users);
        }).catch(error => {
          // 如果发生错误，显示错误信息
          console.error(error);
          // this.$message.error('出现错误，请稍后再试');
        });
      } catch (error) {
        console.error(error);
        // this.$message.error('出现错误，请稍后再试');
      }
    },

    fetch(data) {
      console.log(data)
      // 过滤出 merchantName 为 null 的项
      const filteredData = data.filter(item => item.merchantName === null);

      // 使用 reduce 对数据按 userName 分组，并统计每组的消息数量和时间
      let Chatlist = null;
      Chatlist= filteredData.reduce((groups, item) => {
        // 查找当前分组中是否已有相同 userName 的项
        const group = groups.find(group => group.userName === item.userName);

        if (group) {
          // 如果找到了相同的 userName，将消息数量加 1，并更新最新时间
          group.num += 1;
          group.time = item.createdTime > group.time ? item.createdTime : group.time;
        } else {
          // 如果没有找到相同的 userName，创建一个新的分组
          groups.push({
            userName: item.userName,
            num: 1, // 初始消息数量为 1
            time: item.createdTime // 初始时间
          });
        }
        return groups;
      }, []); // 初始值为空数组
              // // 将 ChatList 存储到 localStorage
      localStorage.setItem('ChatList', JSON.stringify(Chatlist));
      // console.log(Chatlist)
    },

    // 去重用户列表
    removeDuplicateUsers(users) {
      const seen = new Set();
      return users.filter(user => {
        if (seen.has(user.userId)) {
          return false;
        } else {
          seen.add(user.userId);
          return true;
        }
      });
    },

    selectUser(user) {
      this.selectedUser = user;
      Cookie.remove('userid');
      Cookie.set('userid', user.userId, { expires: 7 });
      this.fetchMessages(Cookie.get('userid'));

      // 清除之前的定时器（如果有）
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }

      // 设置新的定时器
      this.intervalId = setInterval(() => {
        this.fetchMessages(Cookie.get('userid'));
      }, 5000);
    },

    // 获取用户聊天记录
    fetchMessages(userId) {
      try {
        // 调用后端 API 获取用户信息
        request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/messages/getMessages?userid=${userId}`,
            METHOD.GET
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token"),
              }
            }
        ).then((response) => {
          const data = response.data && response.data.data;
          if (!data) {
            throw new Error('No data found');
          }

          data.forEach(user => {
            const defaultAvatar = `${window.location.protocol}//${window.location.hostname}:8080/api/uploads/default_avatar.png`;
            user.userAvatar = user.userAvatar && user.userAvatar !== "http://localhost:8080" && user.userAvatar !== `${window.location.protocol}//${window.location.hostname}:8080` ? user.userAvatar : defaultAvatar;
            user.merchantAvatar = user.merchantAvatar && user.merchantAvatar !== "http://localhost:8080" && user.merchantAvatar !== `${window.location.protocol}//${window.location.hostname}:8080` ? user.merchantAvatar : defaultAvatar;
            user.merchantName = user.merchantName ? user.merchantName : "管理员";

            // 如果没有用户名，设置默认用户名
            if (!user.userName) {
              user.userName = "用户" + user.userMobile;
            }
          });
          this.messages = data;
          this.scrollToBottom();
        }).catch(error => {
          // 如果发生错误，显示错误信息
          console.error(error);
          // this.$message.error('出现错误，请稍后再试');
        });
      } catch (error) {
        console.error(error);
        // this.$message.error('出现错误，请稍后再试');
      }
    },

    // 发送消息
    sendMessage() {
      if (this.newMessage.trim() === '') {
        return;
      }
      const userId = this.selectedUser.userId;
      try {
        const message = {
          userid: userId,
          merchantid: Cookie.get("auth_id"),
          messagetext: this.newMessage,
        };
        // 调用后端 API 获取用户信息
        request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/messages/inserttextadmin`,
            METHOD.POST
            , message, {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token"),
              }
            }
        ).then(() => {
          this.newMessage = '';
          this.fetchMessages(userId)
          this.scrollToBottom();
        }).catch(error => {
          // 如果发生错误，显示错误信息
          console.error(error);
          // this.$message.error('出现错误，请稍后再试');
        });
      } catch (error) {
        console.error(error);
        // this.$message.error('出现错误，请稍后再试');
      }
    },
    triggerFileInput() {
      // 触发文件输入框的点击事件
      this.$refs.fileInput.click();
    },
    // 上传图片
    uploadImage(event) {
      const file = event.target.files[0];
      const filename = event.target.files[0].name;
      const userId = this.selectedUser.userId;
      if (file) {
        const formData = new FormData();
        formData.append('imgUrl', file);
        formData.append('fileName', filename)
        formData.append('userid', userId)
        formData.append('merchantid', Cookie.get("auth_id"))

        try {
          // 调用后端 API 获取用户信息
          request(
              `${window.location.protocol}//${window.location.hostname}:8080/api/messages/insertimgesadmin`,
              METHOD.POST
              , formData, {
                headers: {
                  Authorization: `Bearer ` + localStorage.getItem("token"),
                }
              }
          ).then(() => {
            this.fetchMessages(userId)
            this.scrollToBottom(); // 滚动到最新消息
          }).catch(error => {
            // 如果发生错误，显示错误信息
            console.error(error);
            // this.$message.error('出现错误，请稍后再试');
          });
        } catch (error) {
          console.error(error);
          // this.$message.error('出现错误，请稍后再试');
        }
      }
    },
  },
  mounted() {
    this.fetchUsers();
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
}
.user-list ul {
  list-style-type: none; /* 移除默认的列表样式 */
  margin: 0; /* 移除默认的外边距 */
  padding: 0; /* 移除默认的内边距 */
}

/* 左侧用户列表 */
.user-list {
  width: 20%;
  background: #f4f4f4;
  border-right: 1px solid #ddd;
  overflow-y: auto;
  height: 73vh;
}

.user-list li {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
}

.user-list li img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

/* 右侧聊天窗口 */
.chat-window {
  width: 80%;
  display: flex;
  flex-direction: column;
}

.chat-box {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
  max-height: calc(100vh - 67px); /* 减去输入框高度 */
  background-color: #f9f9f9;
  height: 67vh;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
}

.empty-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #aaa;
  font-size: 16px;
}

.chat-message {
  display: flex;
  margin-bottom: 10px;
}

.user-message {
  justify-content: flex-start; /* 用户消息左对齐 */
}

.service-message {
  justify-content: flex-end; /* 客服消息右对齐 */
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 10px;
}

.avatar-right {
  order: 2; /* 客服头像始终在右侧 */
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content-wrapper {
  display: flex;
  flex-direction: column;
}

.message-content-wrapper.content-left {
  align-items: flex-start;
  text-align: left;
}

.message-content-wrapper.content-right {
  align-items: flex-end;
  text-align: right;
}

.message-content {
  padding: 10px;
  border-radius: 10px;
  word-wrap: break-word;
  max-width: 250px;
}

.user-message .message-content {
  background-color: #ff7a45;
  color: white;
}

.service-message .message-content {
  background-color: #e6e6e6;
  color: black;
}

.input-area {
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ddd;
  position: sticky;
  bottom: 0;
}

.upload-icon {
  font-size: 25px;
  padding: 5px;
  color: #ff7a45;
  cursor: pointer;
}

.upload-icon:hover {
  color: #e6733a;
}

.message-input {
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
  margin-right: 10px;
}

.send-button {
  padding: 10px 20px;
  background-color: #ff7a45;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

/* 图片消息通用样式 */
.message-image {
  max-width: 150px; /* 限制图片最大宽度 */
  max-height: 150px; /* 限制图片最大高度 */
  border-radius: 10px; /* 图片圆角 */
  object-fit: cover; /* 图片自适应裁剪 */
  cursor: pointer; /* 鼠标悬浮变成点击状态 */
  transition: transform 0.2s ease; /* 鼠标悬浮动画效果 */
}

.message-image:hover {
  transform: scale(1.1); /* 悬浮时放大 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影 */
}

/* 用户发送的图片消息 */
.user-message .message-image {
  border: 2px solid #ff7a45; /* 用户图片外框颜色 */
  background-color: #fff; /* 背景颜色 */
}

/* 客服发送的图片消息 */
.service-message .message-image {
  border: 2px solid #e6e6e6; /* 客服图片外框颜色 */
  background-color: #fff; /* 背景颜色 */
}

.image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.image-preview-content {
  position: relative;
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.image-preview-content img {
  max-width: 90vw;
  max-height: 80vh;
  border-radius: 10px;
  object-fit: contain;
}

.close-preview {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #ff4d4f;
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.chat-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%; /* 填满整个聊天区域 */
  color: #aaa;
  font-size: 16px;
  text-align: center;
}
.selected-user {
  background-color: #d3f5ff; /* 被选中用户的背景颜色 */
  border-left: 4px solid #13c2c2; /* 左侧边框标识 */
}

/* 商品卡片消息样式优化 */
.product-card-message {
  display: flex;
  align-items: center;
  background-color: #ff7a45;
  color: white;
  border-radius: 10px;
  margin: 5px 0;
  padding: 5px;
}

.product-card-message img {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  margin-right: 10px;
  object-fit: cover;
  cursor: pointer; /* 鼠标悬停时显示为手型 */
}

.product-info-message {
  display: flex;
  flex-direction: column;
}

.product-info-message h3 {
  margin: 0;
  font-size: 11px;
  font-weight: bold;
}

.product-info-message .product-price {
  margin-top: 5px;
  font-size: 14px;
  font-weight: bold;
  color: white;
  text-align: center;
}

/* 商品推荐区域样式优化 */
.product-recommendation {
  margin-bottom: 20px;
}

.product-card {
  width: 55%;
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: box-shadow 0.3s ease;
  float: right;
}

.product-card:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.product-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.product-image {
  width: 150px;
  height: 150px;
  margin-bottom: 10px;
  object-fit: cover;
  border-radius: 5px;
  cursor: pointer; /* 鼠标悬停时显示为手型 */
}

.product-info h3 {
  font-size: 16px;
  color: #333;
  margin: 10px 0;
  text-align: center;
}

.product-price {
  color: #e63946;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}
</style>
